package com.xdf.whiteaccount.async;

import com.xdf.whiteaccount.async.enums.ModuleEnum;
import com.xdf.whiteaccount.async.properties.WechatProp;
import com.xdf.whiteaccount.async.util.WechatPushBodyBuilder;
import com.xdf.whiteaccount.cloudentity.UserMillView;
import com.xdf.whiteaccount.cloudservice.UserMillViewService;
import com.xdf.whiteaccount.config.datasource.DynamicDataSource;
import com.xdf.whiteaccount.dao.CallMapper;
import com.xdf.whiteaccount.dao.CpBillfhMapper;
import com.xdf.whiteaccount.entity.CpBillfh;
import com.xdf.whiteaccount.entity.WechatBody;
import com.xdf.whiteaccount.qrcodeutil.Result;
import com.xdf.whiteaccount.utils.Example;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Future;

/**
 * @program: white-account
 * @description: 色布推送实现类
 * @author: 张柯
 * @create: 2021-06-25 15:39
 **/
@Component
@Slf4j
public class DyeFabricPushNotificationImpl extends BasePushNotification implements IPushNotification {
    private RestTemplate restTemplate;
    private WechatProp wechatProp;
    private UserMillViewService userMillViewService;
    @Autowired
    private CpBillfhMapper cpBillfhMapper;
    @Autowired
    private CallMapper callMapper;
    //@Autowired
    //private DbConfig dbConfig;

    @Autowired
    public void setWechatProp(WechatProp wechatProp) {
        this.wechatProp = wechatProp;
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Autowired
    public void setUserMillViewService(UserMillViewService userMillViewService) {
        this.userMillViewService = userMillViewService;
    }

    /**
     * 色布入库推送
     *
     * @param openIdList openId集合
     * @return
     * @throws Exception
     */
    @Async
    @Override
    public Future<Boolean> pushInbound(List<String> openIdList) throws Exception {
        if (CollectionUtils.isNotEmpty(openIdList)) {
            DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance();
            List<UserMillView> list = userMillViewService.selectByOpenIdList(openIdList);
            Map<String, List<String>> map = getUserMillMap(list);
            for (String u : map.keySet()) {
                if (StringUtils.isNotEmpty(u)) {
                    if (!dynamicDataSource.switchDataSource(u)) continue;
                    List<WechatBody> record = callMapper.selectByModule(ModuleEnum.DYE_FABRIC.getModuleName());
                    Optional.ofNullable(record).orElse(new ArrayList<>()).stream().filter(item -> item.getAccessMode() != null && item.getAccessMode() > 0).forEach(item -> {
                        WechatPushNtfBody body = WechatPushBodyBuilder.buildBody(getWechatBodyFirstParam(item), map.get(u), wechatProp.getTemplateId());
                        try {
                            ResponseEntity<Result> result = restTemplate.postForEntity(wechatProp.getUrl(), body, Result.class);
                            if (result.getStatusCode() == HttpStatus.OK) {
                                cpBillfhMapper.updateByExampleSelective(CpBillfh.builder()
                                        .isPush(true)
                                        .build(), new Example().andEq("id", item.getId()));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.error(e.getMessage());
                        }
                    });
                }
            }
        }
        return new AsyncResult<>(true);
    }

    /**
     * 色布出库推送
     *
     * @param openIdList openId集合
     * @return
     * @throws Exception
     */
    @Async
    @Override
    public Future<Boolean> pushOutbound(List<String> openIdList) throws Exception {
        if (CollectionUtils.isNotEmpty(openIdList)) {
            DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance();
            List<UserMillView> list = userMillViewService.selectByOpenIdList(openIdList);
            Map<String, List<String>> map = getUserMillMap(list);
            for (String u : map.keySet()) {
                if (StringUtils.isNotEmpty(u)) {
                    if (!dynamicDataSource.switchDataSource(u)) continue;
                    List<WechatBody> record = callMapper.selectByModule(ModuleEnum.DYE_FABRIC.getModuleName());
                    Optional.ofNullable(record).orElse(new ArrayList<>()).stream().filter(item -> item.getAccessMode() != null && item.getAccessMode() < 0).forEach(item -> {
                        WechatPushNtfBody body = WechatPushBodyBuilder.buildBody(getWechatBodyFirstParam(item), map.get(u), wechatProp.getTemplateId());
                        try {
                            ResponseEntity<Result> result = restTemplate.postForEntity(wechatProp.getUrl(), body, Result.class);
                            if (result.getStatusCode() == HttpStatus.OK) {
                                cpBillfhMapper.updateByExampleSelective(CpBillfh.builder()
                                        .isPush(true)
                                        .build(), new Example().andEq("id", item.getId()));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.error(e.getMessage());
                        }
                    });
                }
            }
        }
        return new AsyncResult<>(true);
    }
}